package com.lzp.controller;

import com.lzp.pojo.OrderStatus;
import com.lzp.pojo.bo.ShopcartBO;
import com.lzp.pojo.bo.SubmitOrderBO;
import com.lzp.pojo.vo.MerchantOrdersVO;
import com.lzp.pojo.vo.OrderVO;
import com.lzp.service.OrderService;
import com.lzp.utils.*;
import com.lzp.utils.enums.OrderStatusEnum;
import com.lzp.utils.enums.PayMethod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 订单接口
 *
 * @author dtyy
 * @date 2020/9/16
 */
@Api(value = "订单接口", tags = "订单相关接口")
@RequestMapping("orders")
@RestController
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisOperator redis;

    @ApiOperation(value = "用户提交订单", notes = "用户提交订单", httpMethod = "POST")
    @PostMapping("/create")
    public ServerResponse create(@RequestBody SubmitOrderBO submitOrderBO,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        // 1 校验支付方式
        if (submitOrderBO.getPayMethod() != PayMethod.WEIXIN.getCode()
                && submitOrderBO.getPayMethod() != PayMethod.ALIPAY.getCode()) {
            return ServerResponse.createByErrorMsg("支付方式不支持，请选用微信或者支付宝支付");
        }

        // 2 从Redis缓存获取数据，创建订单
        String redisKey = "foodie:shopcart:" + submitOrderBO.getUserId();
        String shopCartJson = redis.get(redisKey);
        if (StringUtils.isBlank(shopCartJson)) {
            return ServerResponse.createByErrorMsg("购物车数据不正确");
        }
        List<ShopcartBO> shopcartBOList = JsonUtils.jsonToList(shopCartJson, ShopcartBO.class);
        OrderVO orderVO = orderService.createOrder(submitOrderBO, shopcartBOList);

        // 3 创建订单后，移除购物车（Redis和前端）中对应商品
        shopcartBOList.removeAll(orderVO.getToBeRemovedShopcatdList());
        redis.set(redisKey, JsonUtils.objectToJson(shopcartBOList));
        CookieUtils.setCookie(request, response, SHOPCART_COOKIE,
                JsonUtils.objectToJson(shopcartBOList), true);

        // 4 向支付中心发送订单
        MerchantOrdersVO merchantOrdersVO = orderVO.getMerchantOrdersVO();
        merchantOrdersVO.setReturnUrl(PAY_RETURN_URL);
        merchantOrdersVO.setAmount(1); // 仅用于测试，1分钱
        // 4.1 构建HTTP请求header
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.add("imoocUserId", "tmp2020");
        httpHeaders.add("password", "tmp2020");
        // 4.2 构建http请求/响应实体
        HttpEntity<MerchantOrdersVO> requestEntity = new HttpEntity<>(merchantOrdersVO, httpHeaders);
        // 4.3 发起请求，并获取响应实体。结果是ServerResponse对象
        // 远端支付中心，返回的是IMOOCJSONResult对象。
        ResponseEntity<IMOOCJSONResult> responseEntity = restTemplate.postForEntity(PAYMENT_URL, requestEntity, IMOOCJSONResult.class);
        IMOOCJSONResult paymentResult = responseEntity.getBody();
        if (paymentResult.getStatus() != 200) {
            return ServerResponse.createByErrorMsg("支付中心创建订单失败，请联系管理员!");
        }

        return ServerResponse.createBySuccess(orderVO.getOrderId());
    }

    /**
     * 微信支付，由支付中心通知后台，不需要返回封装对象
     *
     * @param merchantOrderId 订单id
     * @return
     */
    @PostMapping("notifyMerchantOrderPaid")
    public Integer notifyMerchantOrderPaid(String merchantOrderId) {
        orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.getCode());
        return HttpStatus.OK.value();
    }

    @ApiOperation(value = "微信支付完成后，轮询查询订单状态", notes = "轮询查询订单状态", httpMethod = "POST")
    @PostMapping("getPaidOrderInfo")
    public ServerResponse getPaidOrderInfo(String orderId) {
        OrderStatus orderStatus = orderService.queryOrderStatus(orderId);
        return ServerResponse.createBySuccess(orderStatus);
    }

}
